/**
 * @param {string} url 接口地址
 * @param {string} method 请求方法：GET、POST
 * @param {{}} [params={}] body的请求参数，默认为空
 * @param aes 默认打开加密
 * @param contentType 默认 application/json
 * @return 返回Promise
 */

import config from './config.json';

const __DEV__ = config.Debug;

export const PublishFetch = function<T>(
  url: string,
  method = 'post',
  params?: any,
): Promise<T> {
  let header = {
    'Content-Type': 'application/json',
    version: '1.0',
  };

  if (!url) {
    console.log('请求地址为空'); //打印请求参数
  }

  return new Promise<T>((resolve, reject) => {
    // let handleTimeout = setNetTimeout((v) => {
    //     reject(v);
    // });

    let mTimer = setTimeout(() => {
      const err = {
        status: '1',
        message: '网络超时',
      };
      reject(err);
    }, 1000 * 30);

    let newUrl = url;

    if (params != null && method.toLowerCase() == 'get') {
      let paramsArray = [String()];
      //拼接参数
      Object.keys(params!!).forEach(key =>
        paramsArray.push(key + '=' + params[key]),
      );
      if (newUrl.search(/\?/) === -1) {
        newUrl += '?' + paramsArray.join('&');
      } else {
        newUrl += '&' + paramsArray.join('&');
      }
    }

    // @ts-ignore
    if (__DEV__) {
      console.log('reqUrl:', newUrl, '\nparams:', params, '\nheader:', header); //打印请求参数
    }

    fetch(newUrl, {
      method: method,
      headers: header,
      body: method.toLowerCase() == 'post' ? JSON.stringify(params) : null,
    })
      .then(response => response.json())
      .then(response => {
        clearTimeout(mTimer);
        handleCodeType(url, response, status => {
          if (status) {
            resolve(response);
          } else {
            reject(response);
          }
        });
      })
      .catch(err => {
        clearTimeout(mTimer);
        reject(err);
      });
  });
};

export const paramsToFormData = (params: any) => {
  if (!params) {
    return;
  }

  let fromData = new FormData();

  if (typeof params === 'object') {
    for (let key in params) {
      fromData.append(key, params[key]);
    }
  }
  return fromData;
};

//超时
const setNetTimeout = (doError?: (value: any) => void) => {
  let mTimer = setTimeout(doError => {
    const err = {
      status: '1',
      message: '网络超时',
    };

    if (doError) {
      doError(err);
    }
  }, 1000 * 20);
  return mTimer;
};

// code处理
const handleCodeType = (
  url: string,
  res: any,
  doneCallback: (isOk: boolean) => void,
) => {
  if (__DEV__) {
    console.log('response=>', url, res);
  }
  let code = res.code;
  //用户异常
  if (code == 0) {
    if (doneCallback) {
      doneCallback(true);
    }
  } else {
    if (doneCallback) {
      doneCallback(false);
    }
  }
};
